package com.obixlabs.kalua.datacache;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

import com.hazelcast.core.MapStore;
import com.kalua.list.dbaccess.SimpleCRUDDAO;
import com.kalua.list.domainmodel.Identifiable;
import com.kalua.list.domainmodel.Identifier;

public class DatabaseMapStore <K extends Identifier, V extends Identifiable<K>> 
					implements MapStore <K,V> {

	private SimpleCRUDDAO<V, K> dbAccessObject;
	
	public DatabaseMapStore(SimpleCRUDDAO<V, K> dataAccessObject) 
	{ setDbAccessObject(dataAccessObject); }

	@Override
	public V load(K id) { return this.dbAccessObject.read(id); }

	@Override
	public Map<K, V> loadAll(Collection<K> keys) 
	{ return this.dbAccessObject.readAll(keys); }

	@Override
	public Set<K> loadAllKeys() {
		Set<K> result;
		Map<K, V> allValues = this.dbAccessObject.readAll();
		result = allValues.keySet();
		return result;
	}

	@Override
	public void delete(K key) { this.dbAccessObject.delete(key); }

	@Override
	public void deleteAll(Collection<K> keys) { this.dbAccessObject.deleteAll(keys); }

	@Override
	public synchronized void store(K key, V value) {
		if (value.getId().equals(key))
			this.dbAccessObject.create(value);
		else throw new IllegalArgumentException("Specified key is not the objects identifier"); 
	}

	@Override
	public synchronized void storeAll(Map<K, V> entries) 
	{ this.dbAccessObject.create(entries); }

	public SimpleCRUDDAO<V, K> getDbAccessObject() { return this.dbAccessObject; }
	private void setDbAccessObject(SimpleCRUDDAO<V, K> dataAccessObject) 
	{ this.dbAccessObject = dataAccessObject; }	
}